package org.rexsong.sample.petstore.controllers;

import org.rexsong.sample.petstore.exceptions.PetStoreException;
import org.rexsong.sample.petstore.models.Pet;
import org.rexsong.sample.petstore.repositories.PetRepository;
import org.rexsong.sample.petstore.services.PetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class PetController {

    @Autowired
    private PetService petService;

    @RequestMapping(path = "/add", method = RequestMethod.POST)
    @CacheEvict(cacheNames= {"pets-all", "pets-by-type"}, allEntries=true)
    public long add(@RequestBody Pet pet) throws Exception{
        return petService.save(pet);
    }

    @RequestMapping(path = "/add-bulk", method = RequestMethod.POST)
    @CacheEvict(cacheNames= {"pets-all", "pets-by-type"}, allEntries=true)
    public long add(@RequestBody List<Pet> pets) {
        return petService.saveAll(pets);
    }

    @RequestMapping(path = "/update", method = RequestMethod.POST)
    @CacheEvict(cacheNames= {"pets-all", "pets-by-type"}, allEntries=true)
    public Pet update(@RequestBody Pet pet) {
        petService.save(pet);
        return pet;
    }

    @RequestMapping(path = "/delete/{id}", method = RequestMethod.GET)
    @CacheEvict(cacheNames= {"pets-all", "pets-by-type"}, allEntries=true)
    public long deleteById(@PathVariable("id") final Long id) {
        return petService.deleteById(id);
    }

    @RequestMapping(path= "/list", method = RequestMethod.GET)
    public List<Pet> listAllPets() throws PetStoreException {
        return petService.findAll();
    }

    @RequestMapping(path = "/find/{type}", method = RequestMethod.GET)
    public List<Pet> findByType(@PathVariable("type") final String type) {
        return petService.findByType(type);
    }

    @RequestMapping(path = "/find/status/{status}", method = RequestMethod.GET)
    public List<Pet> findByStatus(@PathVariable("status") final String status) {
        return petService.findByStatus(status);
    }
}
